package com.lepu.app.fun.chat.business;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.database.Cursor;
import android.text.TextUtils;

import com.app.utils.CharacterParser;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.HttpRequest;
import com.core.lib.core.HttpRequest.OnRequestComplete;
import com.lepu.app.fun.chat.activity.DoctorAddActivity;
import com.lepu.app.fun.chat.activity.DoctorMyActivity;
import com.lepu.app.fun.chat.activity.DoctorMyDetailActivity;
import com.lepu.app.fun.chat.bean.BeanDoctorMy;
import com.lepu.app.fun.chat.util.Constants;
import com.lepu.app.fun.chat.util.DbQueryRunner;
import com.lepu.app.main.service.AppService;

public class DoctorManager implements AsyncRequest {

	public static final String REQUEST_DATA = "request_data";
	
	private static DoctorManager mInstance = null;
	
	private DoctorManager()
	{
		
	}
	
	public static DoctorManager getInstance()
	{
		if(mInstance == null)
		{
			mInstance = new DoctorManager();
		}
		return mInstance;
	}
	
	public void requestDoctorList(AsyncRequest asyncRequest) {

		if(!LoginUtil.checkIsLogin())
		{
			return ;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getUserDoctorListUrl(), map, null, asyncRequest,
				REQUEST_DATA, false);
	}
	
	public void requestDoctorDetail(AsyncRequest asyncRequest,String DoctorID) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("DoctorID", DoctorID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getUserDoctorDetailUrl(), map, null, asyncRequest,
				DoctorMyDetailActivity.REQUEST_DATA, true, false, true);
	}

	/**
	 *
	 * @param DoctorID
	 * @param asyncRequest
	 */
	public void requestDoctorDetailRelease(String DoctorID,AsyncRequest asyncRequest) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("DoctorID", DoctorID);

			params.put("PatientID", LoginUtil.getUserId());

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getUserDoctorDetailReleaseUrl(), map, null, asyncRequest,
				"", true);
	}

	public void requestDoctorRelationHistory(AsyncRequest asyncRequest) {

		if(!LoginUtil.checkIsLogin())
		{
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getUserDoctorRelationHistoryUrl(), map, null, asyncRequest,
				AppService.REQUEST_CHECK_DOCTOR_CHANGE, false);
	}

	/**
	 * @param asyncRequest
	 */
	public void requestDoctorSendPhone(AsyncRequest asyncRequest,String UserContent) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("DoctorMobilePhone", UserContent);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.bindDoctorByMobilePhoneUrl(), map, null, asyncRequest,
				DoctorAddActivity.REQUEST_DATA, true);
	}
	
	/**
	 * @param asyncRequest
	 * @param CodeContent
	 */
	public void requestDoctorSendSaoYiSao(AsyncRequest asyncRequest,String CodeContent) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("DoctorCode", CodeContent);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.bindDoctorUrl(), map, null, asyncRequest,
				DoctorMyActivity.REQUEST_DATA_ADD_SAO_YI_SAO, true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if(object.equals(REQUEST_DATA))
		{
			//no main thread
			ArrayList<BeanDoctorMy> dataList = BeanDoctorMy.parseListInfo((String) data);
			if(dataList != null && dataList.size() > 0)
			{
				saveDoctorsDB(dataList);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		if(object.equals(REQUEST_DATA))
		{
			
		}
	}
	
	//==================================
	public boolean saveDoctorsDB(List<BeanDoctorMy> doctors) {
        long currentTime = new Date().getTime();
        DbQueryRunner<?> queryRunner = DbQueryRunner.getInstance();

        if (null != doctors && 0 < doctors.size()) {
            try {
                queryRunner.beginTransaction();
                BeanDoctorMy doctor = null;
                for (int i = 0; i < doctors.size(); i++) {
                    doctor = doctors.get(i);

					char alpha = 0;
					if(!TextUtils.isEmpty(doctor.DoctorName)){
						CharacterParser parser = CharacterParser.getInstance();
						String doctorNameFirst = doctor.DoctorName.substring(0, 1);
						String alphaName = parser.getSelling(doctorNameFirst);

						alpha = alphaName.toCharArray()[0];
					}

					String DepartmentName = doctor.DepartmentName;
					if(TextUtils.isEmpty(DepartmentName)){
						DepartmentName = "";
					}
                    String sql = " REPLACE into Doctor (OriginalId, HostUserId, DoctorId, NickName, ProfilePictureThumbnailId, " +
                            "Age, Gender, LocationCode, Alpha, UpdateTime, HospitialName,DeptmentName,JobTitle,TeachingTitle, Status,CreatedRelationTime,ServiceProductId,ServiceProductName,ServiceProductIconId) " +
                            " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

                    Object params[] = {doctor.DoctorID,
                            LoginUtil.getUserId(),
                            doctor.DoctorID, doctor.DoctorName,
                            doctor.UniqueID, doctor.Age, doctor.Gender,
                            "",
							alpha, String.valueOf(currentTime),
                            doctor.HospitalName,
							DepartmentName,
                            doctor.JobTitle,
                            doctor.TeachJobTitle,
                            doctor.Status,
                            doctor.CreatedRealtionTime,
                            "",
                            "",
                            ""};

                    queryRunner.update(sql, params);
                }
                queryRunner.setTransactionSuccessful();
            } catch (Exception e) {
				e.printStackTrace();
            } finally {
                queryRunner.endTransaction();
            }
        }
        try {
            String sql = "UPDATE Doctor SET Status=? WHERE Status=? AND UpdateTime<?";
            Object[] params = new Object[]{Constants.Relation.RELATION_CODE_RELEASED, Constants.Relation.RELATION_CODE_NORMAL, currentTime};
            queryRunner.update(sql, params);
        } catch (Exception e) {
        }

        return true;
    }
	
	/**
     * 拿到医生列表
     *
     * @param hostUserId
     * @return
     */
    public List<BeanDoctorMy> getDoctorListfromDB(long hostUserId) {
        try {
            String sql = "SELECT * from Doctor where HostUserId = ? and (Status = ? or Status = ? or Status=?) order by Alpha";
            //todo 进行了修改
            String[] params = new String[]{String.valueOf(hostUserId),
                    Constants.Relation.RELATION_CODE_NORMAL_TEXT,
                    Constants.Relation.RELATION_CODE_RELEASED_WAIT,
                    Constants.Relation.RELATION_CODE_RELEASED_TEXT};
			@SuppressWarnings("rawtypes")
			DbQueryRunner queryRunner = DbQueryRunner.getInstance();
            @SuppressWarnings({ "unchecked", "rawtypes" })
			List<BeanDoctorMy> doctors = queryRunner.query(sql, new DbQueryRunner.RowHandler() {
                @Override
                public Object handle(Cursor c) {
                	return BeanDoctorMy.parseDatabase(c);
                }
            }, params);
            return doctors;
        } catch (Exception e) {
            return new ArrayList<BeanDoctorMy>();
        }
    }
    
    public BeanDoctorMy getDoctorfromDB(final long DoctorId) {
        try {
            //todo  status
            String sql = "SELECT * from Doctor where DoctorId = ? And (Status = ? or Status=?) ";
            /// String sql = "SELECT * from Doctor where DoctorId = ? ";
            String[] params = new String[]{String.valueOf(DoctorId),
                    Constants.Relation.RELATION_CODE_NORMAL_TEXT,
                    Constants.Relation.RELATION_CODE_RELEASED_TEXT};
            @SuppressWarnings("rawtypes")
			DbQueryRunner queryRunner = DbQueryRunner.getInstance();
            @SuppressWarnings({ "unchecked", "rawtypes" })
			List<BeanDoctorMy> doctors = queryRunner.query(sql, new DbQueryRunner.RowHandler() {
                @Override
                public Object handle(Cursor c) {
                    
                    return BeanDoctorMy.parseDatabase(c);

                }
            }, params);

            if (0 >= doctors.size()) {
                return null;
            }
            return doctors.get(0);
        } catch (Exception e) {
            return null;
        }
    }

	public boolean updateDoctorRelation(long hostUserId, String doctorId, int relation) {
		try {
			DbQueryRunner<?> queryRunner = DbQueryRunner.getInstance();
			String sql = "UPDATE Doctor SET Status=? WHERE DoctorId=? And HostUserId = ?";

			Object[] params = new Object[]{relation, doctorId, hostUserId};

			queryRunner.update(sql, params);
			return true;

		} catch (Exception e) {
			return false;
		}
	}
   
}
